#include "net.h"

void usage(char* s)
{
	printf("\n %s pls input ip & port",s);
	puts("port must >5000");
}


int main(int argc, char *argv[])
{
	int fd = -1;
	int port =-1;
	if(argc!=3){
		usage(argv[0]);
		exit(1);
	}
	if((fd = socket(AF_INET,SOCK_STREAM,0))<0){
		perror("socket");
		exit(1);
	}
	
	port = atoi(argv[2]);
	if(port <5000){
		usage(argv[0]);
		exit(1);
	}

	struct sockaddr_in sin;
	bzero(&sin,sizeof(sin));
	sin.sin_family = AF_INET;
	sin.sin_port   = htons(port);
	if(inet_pton(AF_INET,argv[1],(void*)&sin.sin_addr)!=1){
		perror("inet_pton");
		exit(1);
	}
	if(connect(fd,(struct sockaddr*)&sin,sizeof(sin))<0){
		perror("connect.");
		exit(1);
	}
	
	int ret =-1;
	int maxfd =fd;
	struct timeval tout;

	fd_set rset,temp;
	FD_ZERO(&rset);
	FD_ZERO(&temp);
	FD_SET(0,&rset);
	FD_SET(fd,&rset);

	char buf[BUFSIZ];

	tout.tv_sec = 6;
	tout.tv_usec = 0;

	while(1)
	{
		temp = rset;
		select(maxfd+1,&temp,NULL,NULL,&tout);
		if(FD_ISSET(0,&temp)){
			bzero(buf,BUFSIZ);
			ret = read(0,buf,BUFSIZ-1);
			if(ret<0){
				perror("read");
				continue;
			}
			else if(!ret)
				continue;
			if(write(fd,buf,strlen(buf))<0){
				perror("write.");
				continue;
			}
			if(!strncasecmp(buf,QUIT_STR,strlen(QUIT_STR))){
				puts("client exit");
				break;
			}
		}
		if(FD_ISSET(fd,&temp)){//服务器发过来的数据
			bzero(buf,BUFSIZ);
			ret = read(fd,buf,BUFSIZ-1);
			if(ret<0){
				perror("read.");
				continue;
			}
			if(!ret)break;//服务器关闭

			printf("ser said:%s\n",buf);
		}
	}
	close(fd);
	return 0;
}

